"""
web 控制台
"""

from flask import Flask, render_template
from flask import current_app, url_for, session, redirect
from flask_oauthlib.client import OAuth

from api import build_buleprint
from core.config import OAUTH2_key, OAUTH2_secret, OAUTH2_URL, SECRET_KEY, WEB_CONSOLE_ADDRESS, WEB_CONSOLE_PORT
from core.decorate import need_login
from solvers import build_solutions
build_solutions()
app = Flask(__name__)
app.register_blueprint(build_buleprint())
app.config['SECRET_KEY'] = SECRET_KEY
oauth = OAuth(current_app)
gitlab = oauth.remote_app('gitlab',
                          consumer_key=OAUTH2_key,
                          consumer_secret=OAUTH2_secret,
                          base_url=OAUTH2_URL,
                          request_token_url=None,
                          request_token_params={'scope': 'read_user'},
                          access_token_url='/oauth/token',
                          authorize_url='/oauth/authorize', )


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@need_login
def index(path):
    return render_template('index.html')


@app.route('/login')
def login():
    return gitlab.authorize(callback=url_for('authorized', _external=True))


@app.route('/authorized')
def authorized():
    resp = gitlab.authorized_response()
    if resp is None:
        return "授权失败"
    session['gitlab_token'] = resp.get('access_token'), ''
    return redirect(url_for('index'))


@app.route('/logout')
def logout():
    if 'gitlab_token' in session:
        session.pop('gitlab_token')
    return "已退出，请同时退出gitlab登陆或取消授权<br>点击链接前往<a href='{}/profile/applications'>gitlab</a>".format(OAUTH2_URL)


@gitlab.tokengetter
def get_gitlab_token(token=None):
    return session.get('gitlab_token')


if __name__ == '__main__':
    # 清理一些临时数据
    from core.documents import TaskProgress

    TaskProgress.drop_collection()
    app.run(debug=True, port=WEB_CONSOLE_PORT, host=WEB_CONSOLE_ADDRESS)
